import { takeEvery, put } from 'redux-saga/effects'
import axios from 'axios'
import { 
  load_todo, load_todo_success,
  add_todo, add_todo_success,
  remove_todo, remove_todo_success, 
  modify_todo, modify_todo_success,
  clear_todo, clear_todo_success,
  modify_todo_edit,
  modify_todo_edit_success,
  modify_todo_name,
  modify_todo_name_success
 } from '../action/todo.action'
/*
  01 完成异步操作
  02 重新发送指令
*/


// 获取列表
function* load_todo_data () {
  let todoData = yield axios.get('/api/todos')
  yield put(load_todo_success(todoData))
}



// 添加 todo

function* add_todo_data (action) {
  console.log(action)
  let taskInfo = yield axios.post('/api/todos', { taskName: action.payload })
  yield put(add_todo_success(taskInfo.task))
}

// 实现 remove_todo_data
function* remove_todo_data (action) {
  // 此时将 id 利用相应的接口传递给后端执行具体的操作
  let res = yield axios.delete('/api/todos', {
    params: {
      id: action.payload
    }
  })
  // 重新发送指令 
  yield put(remove_todo_success(res.tasks.id))
}

// 实现 modify_todo_data
function* modify_todo_data(action) {
  let params = action.payload
  let { task } = yield axios.put('/api/todos/isCompleted', params)
  yield put(modify_todo_success(task))
}

// 实现 clear_todo_data
function* clear_todo_data(action) {
  yield axios.delete('/api/todos/clearCompleted')
  yield put(clear_todo_success())
}

// 实现 modify_todo_eidt_data
function* modify_todo_edit_data(action) {
  let { task } = yield axios.put('/api/todos/isEditing',action.payload)
  yield put(modify_todo_edit_success(action.payload))
}

// 实现 modify_todo_name_data
function* modify_todo_name_data(action) {
  let { task } = yield axios.put('/api/todos', action.payload)
  yield put(modify_todo_name_success(action.payload))
}


export default function* todoSaga() {
  yield takeEvery(load_todo, load_todo_data)
  yield takeEvery(add_todo, add_todo_data)
  yield takeEvery(remove_todo, remove_todo_data)
  yield takeEvery(modify_todo, modify_todo_data)
  yield takeEvery(clear_todo, clear_todo_data)
  yield takeEvery(modify_todo_edit, modify_todo_edit_data)
  yield takeEvery(modify_todo_name, modify_todo_name_data)
}
